package 单链表快速排序;

class ListNode {
    int val;
    ListNode next;

    ListNode(int x) {
        val = x;
    }
}

class Solution {
    public ListNode quickSortList(ListNode head) {
        if (head == null || head.next == null) {
            return head;
        }
        ListNode left = new ListNode(-1);
        ListNode mid = new ListNode(-1);
        ListNode right = new ListNode(-1);
        ListNode ltail = left;
        ListNode mtail = mid;
        ListNode rtail = right;
        int val = head.val;
        for (ListNode p = head; p != null; p = p.next) {
            if (p.val < val) {
                ltail = ltail.next = p;
            } else if (p.val == val) {
                mtail = mtail.next = p;
            } else {
                rtail = rtail.next = p;
            }
        }
        ltail.next = rtail.next = mtail.next = null;
        left.next = quickSortList(left.next);
        right.next = quickSortList(right.next);
        get_tail(left).next = mid.next;
        get_tail(left).next = right.next;
        ListNode ret = left.next;
        left = null;
        mid = null;
        right = null;
        return ret;
    }

    private ListNode get_tail(ListNode head) {
        while (head.next != null) {
            head = head.next;
        }
        return head;
    }
}


